<template>
  <el-form ref="form" :model="form" :rules="rules">
    <el-row>
      <el-col :span='20'>
        <p class='p_hr'>商品价格库存设置
          <el-button type="primary" @click='callPropertyPanel'>变更商品属性</el-button>
          <el-button type="primary" @click='addRow'>添加sku</el-button>
          <!-- <el-button type="primary" @click='test'>校验</el-button> -->
        </p>
        <el-form-item prop='tableData'>
        </el-form-item>
        <div class="el-table el-table--fit el-table--border el-table--enable-row-hover el-table--enable-row-transition">
            <div class="el-table__header-wrapper">
              <table cellspacing="0" cellpadding="0" border="0" class="el-table__header" style="width:100%">
                <thead>
                  <tr>
                    <!-- 渲染属性项表头 -->
                    <th colspan="1" rowspan="1" class="el-table_1_column_1 is-leaf"
                      v-for='item in column.propertyItem'
                    >
                      <div class="cell">{{item.label}}</div>
                    </th>
                    <!-- 渲染基础信息项表头 -->
                    <th colspan="1" rowspan="1" class="el-table_1_column_1 is-leaf"
                      v-for='item in column.baseItem'
                    >
                      <div class="cell">{{item.label}}</div>
                    </th>
                    <!-- 渲染操作项表头 -->
                    <th colspan="1" rowspan="1" class="el-table_1_column_1 is-leaf">
                      操作
                    </th>
                  </tr>
                </thead>
              </table>
            </div>
            <div class="el-table__body-wrapper">
              <table cellspacing="0" cellpadding="0" border="0" class="el-table__body" style="width:100%">
                <tbody>
                  <tr
                    v-for='(rowItem,$rowIndex) in tableData'
                  >
                    <!-- 渲染属性项 -->
                    <td class="el-table_1_column_1"
                      v-for='item in column.propertyItem'
                    >
                      <div class="cell">
                         <el-input v-model="rowItem.propertyItem[item.id]" placeholder="请输入内容"></el-input>
                      </div>
                    </td>
                    <!-- 渲染sku基础信息项 -->
                    <td class="el-table_1_column_1"
                      v-for='item in column.baseItem'
                    >
                      <div class="cell" v-if="item.id !== 'image'">
                         <el-input v-model="rowItem.baseItem[item.id]" placeholder="请输入内容"></el-input>
                      </div>
                      <div class="cell cell_image" v-else>
                         <el-upload
                          class="upload-demo"
                          action="/mall-admin-web/file/uploadImages.do"
                          name='images'
                          :show-file-list=false
                          :on-success='addPic(rowItem.baseItem[item.id],$rowIndex)'
                          >
                          <el-button size="small" type="primary">点击上传</el-button>
                        </el-upload>
                        <img class="cell_image_item" :src="rowItem.baseItem[item.id]" v-if='rowItem.baseItem[item.id]'>
                      </div>
                    </td>
                    <!-- 渲染操作项  -->
                    <td class="el-table_1_column_1">
                      <el-button type="primary" size="small" @click='delRow($rowIndex)'>删除</el-button>
                    </td>
                  </tr>
                </tbody>
              </table>
            </div>
          </div>
      </el-col>
    </el-row>
    <el-dialog title="选择商品属性" v-model="dialogTableVisible">
      <el-form label-width="80px">
        <el-form-item label="商品属性">
          <el-checkbox-group v-model="form.skuCheckList">
            <el-checkbox :label="item" name="skuCheckList" v-for='item in skuProperty'>{{item.foreName}}</el-checkbox>
          </el-checkbox-group>
        </el-form-item>
        <p class="tips_warning">备注：点击【确认】变更商品属性后，所有有关商品的价格和库存等sku信息均需要重新修改。</p>
        <el-form-item>
          <el-button type="primary" @click="onSubmit">立即创建</el-button>
          <el-button @click='onCancle'>取消</el-button>
        </el-form-item>
      </el-form>

    </el-dialog>
  </el-form>
</template>
<script>
  // 校验表格数据是否存在空信息
  function checkItemEmpty (target) {
    // TODO: 改为递归调用
    let flag = 1
    if (!target || target.length === 0) {
      flag = 0
    }
    function checkParamsIsEmpty (params) {
      for (let key in params) {
        if (params[key] === '') {
          return 1
        }
      }
      return 0
    }
    for (let i = 0, len = target.length; i < len; i++) {
      if (checkParamsIsEmpty(target[i].propertyItem) || checkParamsIsEmpty(target[i].baseItem)) {
        flag = 0
        break
      }
    }
    return flag
  }
  import {
    getSkuProperty
  } from 'api'
  export default {
    props: ['categoryid', 'skuListData', 'type'],
    watch: {
      'categoryid': function () {
        if (this.type !== 'edit') {
          this.changeProperty()
        }
      },
      'skuListData': function () {
        if (this.type === 'edit' && this.categoryid) {
          getSkuProperty({
            'catagoryId': this.categoryid
          }).then((res) => {
            if (res.data.code === 100) {
              this.skuProperty = res.data.data
              this.setDefaultData()
            } else {
              this.$alert(res.data.message)
            }
          })
        }
      },
      'tableData': {
        deep: true,
        handler: function () {
          let that = this
          let i
          let len = that.tableData.length
          for (i = 0; i < len; i++) {
            for (let key in that.tableData[i].baseItem) {
              if (key !== 'image') {
                let condition = Number(that.tableData[i].baseItem[key])
                if (Number.isNaN(condition)) {
                  that.$refs.form.validate()
                  break
                }
              }
            }
          }
        }
      }
    },
    data () {
      let that = this
      return {
        skuCheckList: [],
        dialogTableVisible: false,
        skuProperty: [],
        baseColumn: {
          propertyItem: [
          ],
          baseItem: [
            {
              id: 'costPrice',
              label: '商品成本'
            },
            {
              id: 'costExpress',
              label: '物流成本'
            },
            {
              id: 'regularPrice',
              label: '常售价'
            },
            {
              id: 'stock',
              label: '库存'
            },
            {
              id: 'image',
              label: '图片'
            }
          ]
        },
        form: {
          tableData: [],
          skuCheckList: []
        },
        rules: {
          tableData: [
            {
              trigger: 'blur',
              validator: function (rule, value, callback) {
                if (that.tableData.length === 0) {
                  callback(new Error('请添加sku'))
                }
                let condition = checkItemEmpty(that.tableData)
                if (!condition) {
                  callback(new Error('请完整输入sku信息'))
                }
                // 校验表格数据，价格、库存是否是数字
                let i
                let len = that.tableData.length
                for (i = 0; i < len; i++) {
                  for (let key in that.tableData[i].baseItem) {
                    if (key !== 'image') {
                      let condition = Number(that.tableData[i].baseItem[key])
                      if (Number.isNaN(condition)) {
                        callback(new Error('请输入正确的价格库存信息'))
                        break
                      }
                    }
                  }
                }
                callback()
              }
            }
          ]
        },
        fileList: [],
        tableData: []
      }
    },
    computed: {
      column () {
        let columnArr = []
        this.skuCheckList.forEach(function (item, index) {
          let id = item.pid
          let label = item.foreName
          columnArr.push({
            id,
            label
          })
        })
        this.baseColumn.propertyItem = columnArr
        return this.baseColumn
      }
    },
    methods: {
      callPropertyPanel () {
        if (this.categoryid) {
          this.dialogTableVisible = true
        } else {
          this.$alert('请选择类目')
        }
      },
      getFormData () {
        let resultArr = []
        this.tableData.forEach((rowItem, index) => {
          let resultItem = {}
          for (let key in rowItem.baseItem) {
            if (['costPrice', 'costExpress', 'regularPrice'].indexOf(key) > -1) {
              resultItem[key] = rowItem.baseItem[key] * 100
            } else if (['stock'].indexOf(key) > -1) {
              resultItem[key] = rowItem.baseItem[key] * 1
            } else {
              resultItem[key] = rowItem.baseItem[key]
            }
          }
          resultItem['propertyList'] = []
          for (let propertyKey in rowItem.propertyItem) {
            resultItem['propertyList'].push({
              pId: propertyKey,
              propertyValue: rowItem.propertyItem[propertyKey]
            })
          }
          resultArr.push(resultItem)
        })
        return {skuList: resultArr}
      },
      formValidation () {
        let result
        this.$refs.form.validate(function (boolean) {
          result = boolean
        })
        return result
      },
      addRow () {
        let rowModel = {
          propertyItem: {},
          baseItem: {}
        }
        this.column.propertyItem.forEach((item, index) => {
          let key = item.id
          rowModel['propertyItem'][key] = ''
        })
        this.column.baseItem.forEach((item, index) => {
          let key = item.id
          rowModel['baseItem'][key] = ''
        })
        this.tableData.push(rowModel)
      },
      delRow (index) {
        this.$confirm('确认删除该sku？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.tableData.splice(index, 1)
          this.$message({
            type: 'success',
            message: '删除成功!'
          })
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
      },
      addPic (item, rowIndex) {
        let that = this
        return function (response, file, fileList) {
          if (response.code === 100) {
            setTimeout(() => {
              that.tableData[rowIndex].baseItem.image = response.data[0]
            }, 300)
          }
        }
      },
      resetTable () {
        this.form.skuCheckList = []
        this.baseColumn.propertyItem = []
        this.tableData = []
      },
      onSubmit () {
        this.skuCheckList = this.form.skuCheckList
        this.dialogTableVisible = false
        this.resetTable()
      },
      onCancle () {
        this.form.skuCheckList = this.skuCheckList
        this.dialogTableVisible = false
      },
      changeProperty () {
        getSkuProperty({
          'catagoryId': this.categoryid
        }).then((res) => {
          if (res.data.code === 100) {
            this.skuProperty = res.data.data
            this.resetTable()
          } else {
            this.$alert(res.data.message)
          }
        })
      },
      setDefaultData () {
        // 设置sku选中状态
        let skuItem = this.skuListData[0]
        if (skuItem.propertyList.length > 0) {
          skuItem.propertyList.forEach((propItem, index) => {
            let selectedProperty = this.skuProperty.find((item, index2) => {
              return item.pid === propItem.pId
            })
            this.form.skuCheckList.push(selectedProperty)
            this.skuCheckList = this.form.skuCheckList
          })
        }
        // 设置表格数据
        this.skuListData.forEach((item, index) => {
          let row = {}
          row['baseItem'] = {}
          row['propertyItem'] = {}
          for (let key in item) {
            if (key !== 'propertyList') {
              if (['costPrice', 'costExpress', 'regularPrice'].indexOf(key) > -1) {
                row['baseItem'][key] = item[key] / 100
              } else if (['stock'].indexOf(key) > -1) {
                row['baseItem'][key] = item[key]
              } else {
                row['baseItem'][key] = item[key]
              }
            }
          }
          if (item['propertyList'].length > 0) {
            item['propertyList'].forEach((propItem, index) => {
              row['propertyItem'][propItem.pId] = propItem.propertyValue
            })
          }
          this.tableData.push(row)
        })
      }
    }
  }
</script>
<style>
  .tips_warning{
    color: #F7BA2A
  }
  .cell_image_item {
    width: 150px!important;
    height: 150px!important;
    cursor: pointer;
  }
</style>
